package com.cqndt.site.shrio;

import com.cqndt.site.vo.SysUserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

@Component
public class ShiroUtils {
    /**  加密算法 */
    public final static String hashAlgorithmName = "SHA-256";
    /**  循环次数 */
    public final static int hashIterations = 16;

    public static Session getSession(){
        return SecurityUtils.getSubject().getSession();
    }

    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }
    public static SysUserVo getUserEntity() {
        return (SysUserVo)SecurityUtils.getSubject().getPrincipal();
    }
    public static Integer getUserId() {
        return getUserEntity().getId();
    }

    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    public static String getKaptcha(String key) throws Exception {
        Object kaptcha = getSessionAttribute(key);
        if(kaptcha == null){
            throw new Exception("验证码已失效");
        }
        //getSession().removeAttribute(key);
        return kaptcha.toString();
    }
}
